<template>
  <div class="funding-source-detail">
    <el-card shadow="never" class="detail-card">
      <template #header>
        <div class="card-header">
          <span>出资方详情</span>
          <el-button @click="goBack" text>返回列表</el-button>
        </div>
      </template>

      <!-- 基本信息 -->
      <el-descriptions title="基本信息" :column="3" border>
        <el-descriptions-item label="出资方ID">{{ fundingSourceDetail.id }}</el-descriptions-item>
        <el-descriptions-item label="出资方名称">{{ fundingSourceDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ fundingSourceDetail.contactName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ fundingSourceDetail.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="合作状态">
          <el-tag :type="getStatusType(fundingSourceDetail.status)">
            {{ formatStatus(fundingSourceDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ fundingSourceDetail.createTime }}</el-descriptions-item>
      </el-descriptions>

      <!-- 资金信息 -->
      <el-descriptions title="资金信息" :column="2" border style="margin-top: 20px;">
        <el-descriptions-item label="资金总额度">{{ formatAmount(fundingSourceDetail.totalAmount) }}</el-descriptions-item>
        <el-descriptions-item label="固定额度">{{ formatAmount(fundingSourceDetail.fixedAmount) }}</el-descriptions-item>
        <el-descriptions-item label="浮动额度">{{ formatAmount(fundingSourceDetail.floatingAmount) }}</el-descriptions-item>
        <el-descriptions-item label="已用额度">{{ formatAmount(fundingSourceDetail.usedAmount) }}</el-descriptions-item>
        <el-descriptions-item label="剩余额度">{{ formatAmount(fundingSourceDetail.remainingAmount) }}</el-descriptions-item>
        <el-descriptions-item label="使用率">
          <el-progress :percentage="calculateUsageRate(fundingSourceDetail)" :status="getProgressStatus(fundingSourceDetail)" />
        </el-descriptions-item>
      </el-descriptions>

      <!-- 合作项目信息 -->
      <div class="project-info" style="margin-top: 20px;">
        <div class="section-title">
          <span>合作项目列表</span>
        </div>
        <el-table :data="projectList" style="width: 100%" border :header-cell-style="{ background: '#f5f7fa' }">
          <el-table-column prop="projectName" label="项目名称" min-width="150" />
          <el-table-column prop="startTime" label="开始日期" width="120" />
          <el-table-column prop="endTime" label="结束日期" width="120" />
          <el-table-column label="项目金额" width="150" align="right">
            <template #default="scope">
              {{ formatAmount(scope.row.amount) }}
            </template>
          </el-table-column>
          <el-table-column label="项目状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getProjectStatusType(scope.row.status)">
                {{ formatProjectStatus(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button type="primary" link @click="viewProjectDetail(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 备注信息 -->
      <el-descriptions title="备注信息" :column="1" border style="margin-top: 20px;" v-if="fundingSourceDetail.remark">
        <el-descriptions-item>{{ fundingSourceDetail.remark }}</el-descriptions-item>
      </el-descriptions>

      <!-- 资金变动趋势图 -->
      <div class="trend-chart" style="margin-top: 20px;">
        <div class="section-title">
          <span>资金变动趋势</span>
        </div>
        <div ref="chartRef" style="width: 100%; height: 350px;"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';

const route = useRoute();
const router = useRouter();
let chart: echarts.ECharts | null = null;

// 出资方详情
const fundingSourceDetail = ref({
  id: '',
  name: '',
  contactName: '',
  contactPhone: '',
  status: '',
  createTime: '',
  totalAmount: 0,
  fixedAmount: 0,
  floatingAmount: 0,
  usedAmount: 0,
  remainingAmount: 0,
  remark: ''
});

// 合作项目列表
const projectList = ref([]);

// 图表引用
const chartRef = ref();

// 初始化数据
onMounted(() => {
  const id = route.params.id;
  if (id) {
    fetchFundingSourceDetail(id as string);
  }

  // 窗口大小变化时，重新调整图表大小
  window.addEventListener('resize', handleResize);
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (chart) {
    chart.dispose();
    chart = null;
  }
});

// 窗口大小变化处理
const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};

// 获取出资方详情
const fetchFundingSourceDetail = (id: string) => {
  // 模拟从服务器获取数据
  setTimeout(() => {
    // 模拟出资方详情数据
    const fixedAmount = Math.floor(Math.random() * 9 + 1) * 1000000;
    const floatingAmount = Math.floor(Math.random() * 5 + 1) * 500000;
    const totalAmount = fixedAmount + floatingAmount;
    const usedAmount = Math.floor(Math.random() * fixedAmount);
    const remainingAmount = totalAmount - usedAmount;

    fundingSourceDetail.value = {
      id,
      name: `出资方${id}`,
      contactName: `联系人${id}`,
      contactPhone: `1381234${id.toString().padStart(4, '0')}`,
      status: Number(id) % 3 === 0 ? 'paused' : (Number(id) % 5 === 0 ? 'terminated' : 'active'),
      createTime: '2024-02-15 14:30:25',
      totalAmount,
      fixedAmount,
      floatingAmount,
      usedAmount,
      remainingAmount,
      remark: `这是出资方${id}的详细备注信息，包含了合作历史和重要事项说明。该出资方于2024年初开始合作，主要负责提供小额贷款业务的资金支持。`
    };

    // 加载合作项目列表
    loadProjectList(id);

    // 初始化图表
    initChart();
  }, 500);
};

// 加载合作项目列表
const loadProjectList = (id: string) => {
  // 模拟项目数据
  const mockProjects = [];
  for (let i = 1; i <= 5; i++) {
    const startDate = new Date();
    startDate.setMonth(startDate.getMonth() - i * 2);
    
    const endDate = new Date(startDate);
    endDate.setMonth(endDate.getMonth() + 12);
    
    mockProjects.push({
      id: `${id}-${i}`,
      projectName: `项目${i}`,
      startTime: formatDate(startDate),
      endTime: formatDate(endDate),
      amount: Math.floor(Math.random() * 5 + 1) * 200000,
      status: i === 1 ? 'ongoing' : (i === 5 ? 'completed' : (i % 3 === 0 ? 'planning' : 'ongoing'))
    });
  }
  projectList.value = mockProjects;
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  // 销毁旧图表
  if (chart) {
    chart.dispose();
  }

  // 创建图表实例
  chart = echarts.init(chartRef.value);

  // 模拟过去6个月的数据
  const now = new Date();
  const months = [];
  const usedData = [];
  const remainingData = [];
  const totalData = [];

  for (let i = 5; i >= 0; i--) {
    const date = new Date(now);
    date.setMonth(date.getMonth() - i);
    months.push(`${date.getFullYear()}/${date.getMonth() + 1}`);

    const baseTotal = fundingSourceDetail.value.totalAmount;
    const factor = Math.min(1, Math.max(0.1, (6 - i) / 6));
    const used = Math.floor(fundingSourceDetail.value.usedAmount * factor);
    
    usedData.push(used);
    remainingData.push(baseTotal - used);
    totalData.push(baseTotal);
  }

  // 设置图表配置项
  const option = {
    title: {
      text: '资金使用趋势图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params: any[]) {
        let result = params[0].name + '<br/>';
        for (let i = 0; i < params.length; i++) {
          const param = params[i];
          const marker = `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>`;
          const value = formatAmount(param.value).replace('¥', '');
          result += marker + param.seriesName + ': ' + value + '<br/>';
        }
        return result;
      }
    },
    legend: {
      data: ['已用额度', '剩余额度', '总额度'],
      bottom: '0%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: months
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: function(value: number) {
          return (value / 10000) + '万';
        }
      }
    },
    series: [
      {
        name: '已用额度',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: usedData
      },
      {
        name: '剩余额度',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: remainingData
      },
      {
        name: '总额度',
        type: 'line',
        emphasis: {
          focus: 'series'
        },
        data: totalData
      }
    ]
  };

  // 设置图表选项
  chart.setOption(option);
};

// 返回列表
const goBack = () => {
  router.push('/funding-source/list');
};

// 格式化金额
const formatAmount = (amount: number) => {
  return amount.toLocaleString('zh-CN', { style: 'currency', currency: 'CNY' });
};

// 格式化日期
const formatDate = (date: Date) => {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 格式化状态
const formatStatus = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'active': '合作中',
    'paused': '已暂停',
    'terminated': '已终止'
  };
  return statusMap[status] || '未知';
};

// 获取状态标签类型
const getStatusType = (status: string) => {
  const typeMap: { [key: string]: 'success' | 'warning' | 'danger' | 'info' } = {
    'active': 'success',
    'paused': 'warning',
    'terminated': 'danger'
  };
  return typeMap[status] || 'info';
};

// 计算资金使用率
const calculateUsageRate = (data: { usedAmount: number, totalAmount: number }) => {
  if (!data.totalAmount) return 0;
  return Math.round((data.usedAmount / data.totalAmount) * 100);
};

// 获取进度条状态
const getProgressStatus = (data: { usedAmount: number, totalAmount: number }) => {
  const rate = calculateUsageRate(data);
  if (rate >= 90) return 'danger';
  if (rate >= 70) return 'warning';
  if (rate >= 50) return 'primary';
  return 'success';
};

// 格式化项目状态
const formatProjectStatus = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'planning': '筹划中',
    'ongoing': '进行中',
    'completed': '已完成'
  };
  return statusMap[status] || '未知';
};

// 获取项目状态标签类型
const getProjectStatusType = (status: string) => {
  const typeMap: { [key: string]: 'success' | 'warning' | 'primary' | 'info' } = {
    'planning': 'warning',
    'ongoing': 'primary',
    'completed': 'success'
  };
  return typeMap[status] || 'info';
};

// 查看项目详情
const viewProjectDetail = (project: any) => {
  ElMessage.info(`查看项目详情: ${project.projectName}`);
  // 实际项目中应跳转到项目详情页
  // router.push(`/project/detail/${project.id}`);
};
</script>

<style scoped>
.funding-source-detail .detail-card {
  margin-bottom: 20px;
}

.funding-source-detail .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.funding-source-detail .section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
  color: var(--el-text-color-primary);
  font-weight: 500;
}

.funding-source-detail .trend-chart {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}
</style> 